package org.fuys.coder.application;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.fuys.coder.common.entity.Result;
import org.fuys.coder.common.constants.ResultMessageConstants;
import org.fuys.coder.common.exception.BusinessException;
import org.fuys.coder.common.holder.UserHolder;
import org.fuys.coder.domain.file.service.AliYunOSSService;
import org.fuys.coder.domain.file.service.AliYunStsTokenService;
import org.fuys.coder.domain.file.service.IFileService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.application
 * @className: FileController
 * @author: WangJing
 * @description: 文件控制器
 * @date: 2024/6/28 21:51
 * @version: 1.0
 */

@RestController
@RequestMapping("/fuyscoder/file")
public class FileController {

    @Resource
    private AliYunStsTokenService tokenService;

    @Resource
    private AliYunOSSService ossService;

    @Resource
    private IFileService fileService;

    //todo 也许可以做限流处理？
    @GetMapping("/uploadToken")
    public Result getUploadToken(){
        try {
            return Result.ok().data(tokenService.getStsToken());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error(ResultMessageConstants.FILE_TOKEN_FAILED);
    }

    @GetMapping("/saveFile")
    public Result save(@RequestParam("fileName") String fileName,
                       @RequestParam("type") String type){
        Integer userId= UserHolder.get();
        if(ObjectUtils.isEmpty(userId)){
            throw new BusinessException(ResultMessageConstants.NO_USER_TOKEN);
        }
        //这里要先检查云端是否存在这个文件 然后进行保存文件表操作
        if (!ossService.doesDataExist(fileName)) {
            //如果不存在 返回给前端信息 让用户检查
            return Result.error(ResultMessageConstants.FILE_UPLOAD_NOT_FOUND);
        }else{
            final int save = fileService.save(fileName, type, userId);
            return Result.ok().data(save);
        }
    }

    //todo  下面是获取文件内容的接口 不过之后会增加防盗链的设置
    @GetMapping("/other")
    public Result otherFile(Long id){
        final String url = ossService.buildUrl(id);
        return Result.ok().data(url);
    }

    @GetMapping("/media")
    public Result mediaFile(Long id){
        final String url = ossService.buildUrl(id);
        return Result.ok().data(url);
    }

    @PostMapping("/multi")
    public Result multipleFile(@RequestBody List<Long> ids){
        final List<String> strings = ossService.buildUrl(ids);
        return Result.ok().data(strings);
    }


}
